package org.example.provider.triple.impl;

import com.google.protobuf.Any;
import com.google.protobuf.BoolValue;
import com.google.protobuf.InvalidProtocolBufferException;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.rpc.RpcException;
import org.example.provider.triple.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.Date;
import java.util.function.Function;

//@DubboService(group = "group1",version = "1.0",registry = "testRegistry")
@DubboService(group = "group1", version = "1.0", loadbalance = "cid")
//@DubboService(group = "group1", version = "1.0")
public class GreeterImpl extends DubboGreeterServiceTriple.GreeterServiceImplBase {

    public static void main(String[] args) throws InvalidProtocolBufferException {
        Any pack = Any.pack(BoolValue.of(true));
        BoolValue unpack = pack.unpack(BoolValue.class);
        boolean value = unpack.getValue();
        System.out.println(value);
    }

    @Override
    public Mono<GenericMessage> anyDemo(Mono<GreeterRequest> request) {
        GreeterReply greeterReply = GreeterReply.newBuilder().setMessage("Hello privder get name :" + request.block().getName()).build();
        ExampleMessage example = ExampleMessage.newBuilder().setName("niubi").build();
        return Mono.just(GenericMessage.newBuilder()
                .setData(Any.pack(BoolValue.of(true)))
                .setExample(example)
                .build()
        );
    }

    @Override
    public Mono<GreeterReply> greetOneToOne(Mono<GreeterRequest> request) {
        return request.map(req -> {
                    System.out.println("greetOneToOne: " + req.getName());
                    if (true) {
                        throw new RpcException("RpcException test");
                    }
                    return GreeterReply.newBuilder().setMessage("Hello privder get name :" + req.getName()).build();
                })
                .onErrorResume(e -> {
                    System.out.println("error: " + e.getMessage());
                    return Mono.just(GreeterReply.newBuilder().setMessage("error").build());
                })
                ;
    }



    @Override
    public Flux<GreeterReply> greetManyToMany(Flux<GreeterRequest> request) {
        return request.map(req -> {
            System.out.println("greetManyToMany: " + req.getName());
            return GreeterReply.newBuilder().setMessage("Hello privder get name :" + req.getName()).build();
        }).repeat(2);
    }
}
